/*
 * @Date         : 2024-05-12 17:40:38 星期0
 * @Author       : xut
 * @Description  :
 */
import { resolve } from "node:path"
import grpc from "@grpc/grpc-js"
import { loadProto } from "../utils/loadProto.js"

const PROTO_PATH = resolve(process.cwd(), "./echo.proto")
const echoProtoDescriptor = loadProto(PROTO_PATH)
const echoProto = echoProtoDescriptor.echo

const channelOptions = {
  // If a client is idle for 15 seconds, send a GOAWAY
  // 如果客户端空闲时间超过10秒，则断开
  "grpc.max_connection_idle_ms": 10_000,
  // If any connection is alive for more than 30 seconds, send a GOAWAY
  // 如果任何连接存活的时间超过20秒，则发送断开消息
  "grpc.max_connection_age_ms": 20_000,
  // Allow 5 seconds for pending RPCs to complete before forcibly closing connections
  // 在强制关闭连接之前，允许再等待的rpc 5秒
  // "grpc.max_connection_age_grace_ms": 5_000,
  // Ping the client every 5 seconds to ensure the connection is still active
  // 每5秒Ping一次客户端，确保连接仍处于活动状态
  // "grpc.keepalive_time_ms": 5_000,
  // Wait 1 second for the ping ack before assuming the connection is dead
  // 如果等待1秒钟后仍没有收到ping回复，连接断开
  // "grpc.keepalive_timeout_ms": 1_000,
}
const server = new grpc.Server(channelOptions)

const echoServiceImpl = {
  unaryEcho: (call, cb) => {
    call.on("error", (error) => {
      console.log(`Server Error: ${JSON.stringify(error)}`)
    })

    call.on("end", () => {
      console.log("server end ")
    })

    const message = call.request.message

    if (message.startsWith("delay")) {
      setTimeout(() => {
        cb(null, call.request)
      }, 2000)
    } else {
      cb(null, call.request)
    }
  },
}

server.addService(echoProto.Echo.service, echoServiceImpl)
server.bindAsync(
  "localhost:50051",
  grpc.ServerCredentials.createInsecure(),
  (err, port) => {
    if (err !== null) {
      return console.error(err)
    }

    console.log("gRPC listening on localhost:" + port)
  }
)
